import { getOpenKeysFromLocal, setOpenKeysToLocal } from '@renderer/store/localstorage'

import { openKeysAtom } from '@renderer/store/jotai'
import { ref } from 'vue'
import { useAtom } from 'jotai-vue'

export default function useOpenKeys() {
  const [openKeys, setOpenKeys] = useAtom(openKeysAtom)

  const addOpenKeys = (keys) => {
    const currentOpenKeys = getOpenKeysFromLocal()

    let notChanged = true

    keys.forEach((key) => {
      if (!currentOpenKeys.includes(key)) {
        notChanged = false
      }
    })

    if (notChanged) return

    const newKeys = [...currentOpenKeys, ...keys].filter((item) => !!item)

    setOpenKeys(newKeys)
    setOpenKeysToLocal(newKeys)
  }

  const removeOpenKey = (key) => {
    const currentOpenKeys = getOpenKeysFromLocal()
    const newKeys = currentOpenKeys.filter((_key) => _key !== key)

    setOpenKeys(newKeys)
    setOpenKeysToLocal(newKeys)
  }

  return {
    openKeys: ref(openKeys),
    setOpenKeys,
    addOpenKeys,
    removeOpenKey
  }
}
